package com.xfusion.chatglm.data.domain.openai.service.rule.impl;

import com.google.common.cache.Cache;
import com.xfusion.chatglm.data.domain.openai.annotation.LogicStrategy;
import com.xfusion.chatglm.data.domain.openai.model.aggregates.ChatProcessAggregate;
import com.xfusion.chatglm.data.domain.openai.model.entity.RuleLogicEntity;
import com.xfusion.chatglm.data.domain.openai.model.entity.UserAccountQuotaEntity;
import com.xfusion.chatglm.data.domain.openai.model.valobj.LogicCheckTypeVO;
import com.xfusion.chatglm.data.domain.openai.service.rule.ILogicFilter;
import com.xfusion.chatglm.data.domain.openai.service.rule.factory.DefaultLogicFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @description:访问次数过滤器
 * 访问次数限制
 * @LogicStrategy自定义注解，标记这个过滤器的逻辑模式为ACCESS_LIMIT（次数限制）
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.ACCESS_LIMIT)
public class AccessLimitFilter implements ILogicFilter<UserAccountQuotaEntity> {
    @Value("${app.config.limit-count:10}")
    private Integer limitCount;
    @Value("${app.config.white-list}")
    private String whiteListStr;
    @Resource
    private Cache<String,Integer>visitCache;//用于访问缓存
    @Override
    public RuleLogicEntity<ChatProcessAggregate> filter(ChatProcessAggregate chatProcessAggregate, UserAccountQuotaEntity data) throws Exception {
        //白名单用户直接放行
        if (chatProcessAggregate.isWhiteList(whiteListStr)){
            return RuleLogicEntity.<ChatProcessAggregate>builder()
                    .type(LogicCheckTypeVO.SUCCESS).data(chatProcessAggregate).build();
        }
        String openId = chatProcessAggregate.getOpenid();

        //个人账户不为空，不做系统访问次数拦截
        if (null!=data){
            return RuleLogicEntity.<ChatProcessAggregate>builder().type(LogicCheckTypeVO.SUCCESS).data(chatProcessAggregate).build();
        }

        //访问次数判断
        int visitCount = visitCache.get(openId,()->0);
        //访问次数没有超过限制，就增加访问次数并放行
        if (visitCount<limitCount){
            visitCache.put(openId,visitCount+1);
            return RuleLogicEntity.<ChatProcessAggregate>builder()
                    .type(LogicCheckTypeVO.SUCCESS).data(chatProcessAggregate).build();
        }
        //超过限制就拦截
        return RuleLogicEntity.<ChatProcessAggregate>builder()
                .info("您今日的免费"+limitCount+"次，已耗尽!")
                .type(LogicCheckTypeVO.REFUSE).data(chatProcessAggregate).build();
    }
}
